﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Beway.ValueAdded.Model;
using System.Data.SqlClient;
using System.Data;
using System.Net;
using System.IO;
using System.Xml;
using Beway.ValueAdded.Util;
using System.Web;
using System.Transactions;
using Beway.ValueAdded.Model.ViewModel;
using System.Security.Cryptography;
using System.Configuration;


namespace Beway.ValueAdded.Service
{
    public class RechargeServ
    {
        //与欧飞约定的keystr
        private const string Ofkeystr= "A867800E321FE5AB";    //hanve keystr                 
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //移动手机号前3位
        private static readonly string[] ChinaMobileNoPrefix = new string[]{
            "134",
            "135",
            "136",
            "137",
            "138",
            "139",
            "150",
            "151",
            "152",
            "157",
            "158",
            "159",
            "178",
            "182",
            "183",
            "184",
            "187",
            "188",
            "147"
        };


        /// <summary>
        /// 接收到支付成功结果后，更新订单支付状态
        /// </summary>
        /// <param name="OrderID">订单号</param>
        /// <param name="OrderAmount">支付金额</param>
        /// <returns></returns>
        public int PayStatusUpdate(string OrderID, decimal OrderAmount)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                SqlParameter ParamOrderID = new SqlParameter("@OrderID", SqlDbType.VarChar);
                ParamOrderID.Direction = ParameterDirection.Input;
                ParamOrderID.Value = OrderID;

                SqlParameter ParamOrderAmount = new SqlParameter("@OrderAmount", SqlDbType.Money);
                ParamOrderAmount.Direction = ParameterDirection.Input;
                ParamOrderAmount.Value = OrderAmount;

                int ret = db.Database.SqlQuery<Int32>("EXECUTE PayResultTrans @OrderID,@OrderAmount", new SqlParameter[] { ParamOrderID, ParamOrderAmount }).FirstOrDefault();
                return ret;
            }
        }


        /// <summary>
        /// 更新充值状态
        /// </summary>
        /// <param name="rcid">充值记录主键</param>
        /// <param name="rechargestatus">1充值成功,9充值失败</param>
        /// <param name="errmsg">失败时的原因</param>
        /// <returns></returns>
        public bool RechargeStatusUpdate(int rcid, int rechargestatus, string errmsg)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                Recharge rc = db.Recharge.Where(r => r.RCID == rcid).SingleOrDefault();
                if (rc.RCID > 0)
                {
                    rc.RechargeStatus = rechargestatus;
                    rc.RechargeSuccessTime = System.DateTime.Now;//如果充值失败，则为失败时间
                    rc.RechargeErrorReason = errmsg;
                    int i = db.SaveChanges();
                    return i > 0;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 接收ofcard服务器端通知的充值结果
        /// </summary>
        /// <param name="OrderID">订单号</param>
        /// <param name="rechargstatus">充值状态1成功，9失败（可退款)</param>
        /// <param name="err_msg">失败原因</param>
        /// <returns></returns>
        public int RechargeResultReceive(string OrderID, int rechargestatus, string err_msg)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                Recharge rc = db.Recharge.Where(r => r.OrderID == OrderID).SingleOrDefault();
                if (rc.RCID > 0)
                {
                    if (rc.RechargeStatus != 1)
                    {
                        int retStatus = rechargestatus;
                        if (rechargestatus == 9)//欧飞返回充值失败
                        {
                            retStatus = 3;//充值平台的状态码为3，充值失败
                        }

                        rc.RechargeStatus = retStatus;
                        rc.RechargeSuccessTime = System.DateTime.Now;
                        //rc.RechargeErrorReason +=err_msg;
                        rc.RechargeErrorReason = err_msg;
                        int i = db.SaveChanges();
                        return i;//更新成功
                    }
                    else
                    {
                        return 0;//不需要更新（已经收到通知)
                    }
                }
                else
                    return -1;//没找到此订单

            }
        }

        /// <summary>
        /// 欧飞话费充值业务/欧飞Q币业务充值
        /// </summary>
        /// <param name="recharge"></param>
        /// <param name="user">项目信息</param>
        /// <returns></returns>
        public string RechargeTrade(Recharge recharge, ReUser user)
        {
            //话费类的 
            if (recharge.RCType == 1)
            {
                bool isDiscount = false;
                Random rnd = new Random(System.Guid.NewGuid().GetHashCode());
                int rndRate = rnd.Next(0, 100);

                if (user.RechDiscountRate > 0 && rndRate < user.RechDiscountRate)
                {
                    isDiscount = true;
                }
                if (!isDiscount)
                {
                    return RechargeTrade(recharge); 
                }
                else
                {
                    recharge.RechargeStatus = 1;//充值成功
                    recharge.RechargeSuccessTime = System.DateTime.Now;
                    recharge.RechDiscountFlag = 1;//优化标志
                    return recharge.RechargeStatus.ToString();
                }
            }
            else
            {        
                //qq币
                return RechargeTrade(recharge);
            }
        }


        /// <summary>
        /// 充值业务(如url发送支付信息后，不能得到充值结果，欧飞还将调用ret_url中的地址，通知充值结果
        /// </summary>
        /// <param name="_ORDERID"></param>
        /// <returns>欧飞返回码 0充值中, 1成功, 9充值失败，可以退款, 11运营商维护，暂不能充值</returns>
        private string RechargeTrade(Recharge recharge)
        {
            string rechargeurl = "http://api2.ofpay.com/onlineorder.do?userid={0}&userpws={1}&cardid={2}&cardnum={3}&sporder_id={4}&sporder_time={5}&game_userid={6}&md5_str={7}&ret_url={8}&version=6.0";
            log4net.Config.XmlConfigurator.Configure();

            // log.Error("测试");

            string ret_url = "http://" + Config.SiteUrl + "/Recharge/RecResult";//欧飞通知的结果
            string SendUrl = "";
            int rcid = 0;
            string ret = "";

            // Recharge recharge = db.Recharge.Where(r => r.OrderID == _ORDERID).SingleOrDefault() ;
            if (recharge != null && recharge.RCID > 0)
            {
                rcid = recharge.RCID;
                string ordertime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
                string cardid = "140101";//手机充值
                if (recharge.RCType == 2)//q币任意
                {
                    cardid = "220612";
                }
             
                //userid+userpws+cardid+cardnum+sporder_id+sporder_time+ game_userid

                string md5str = beway.common.Encryption.Md5Encry32bit(Config.ofUserID + Config.ofPwd + cardid + recharge.RechargeAmount + recharge.OrderID + ordertime + recharge.RCTarget + Ofkeystr).ToUpper();
                SendUrl = string.Format(rechargeurl, Config.ofUserID, Config.ofPwd, cardid, recharge.RechargeAmount, recharge.OrderID, ordertime, recharge.RCTarget, md5str, ret_url);

            }

            if (SendUrl != "")
            {
                HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(SendUrl);
                webRequest.ContentType = "application/xml; charset=utf-8";
                webRequest.Method = "get";
                try
                {
                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("gb2312")))
                    {
                        XmlDocument doc = new XmlDocument();
                        string ss = sr.ReadToEnd();
                        //记录到log
                        log.Info(ss);

                        doc.LoadXml(ss);
                        string retcode = doc.SelectSingleNode("//orderinfo/retcode").InnerText;//状态码
                        string rc = "", errmsg = "";
                        if (retcode == "1")//成功
                        {
                            //game_state有可能的值 0充值中，1充值成功，9充值撤销（可退款）
                            rc = doc.SelectSingleNode("//orderinfo/game_state").InnerText;//提交成功，true
                        }
                        else
                        {
                            errmsg = doc.SelectSingleNode("//orderinfo/err_msg").InnerText;//失败时的原因
                            recharge.RechargeErrorReason = errmsg;
                            rc = retcode;//可能的值 0充值中,  1成功, 9充值失败，可以退款, 11运营商维护，暂不能充值
                        }

                        if (rc == "1")
                        {
                            recharge.RechargeStatus = 1;//充值成功
                        }
                        else if (rc == "0")
                        {
                            recharge.RechargeStatus = 2;//充值中
                            recharge.RechargeErrorReason = "正在充值中";
                        }
                        else if (rc == "9")
                        {
                            recharge.RechargeStatus = 3;//充值失败，可以退款
                        }
                        else if (rc == "11") //运营商维护也返回3
                        {
                            recharge.RechargeStatus = 3;
                        }
                        else//等于空的情况
                        {
                            recharge.RechargeStatus = 0;//错误
                            recharge.RechargeErrorReason = "充值平台返回结果未知(retcode:" + rc + ")";
                        }
                        recharge.RechargeSuccessTime = System.DateTime.Now;

                        //20140630改为直接接收码, 0充值中,  1成功, 9充值失败，可以退款, 11运营商维护，暂不能充值
                        ret = rc;

                        sr.Close();
                        sr.Dispose();
                    }
                    webResponse.Close();
                }
                catch (Exception ex)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("****************************\r\n");
                    sb.Append("充值异常时间：" + System.DateTime.Now.ToString() + "\r\n");
                    sb.Append("订单号：" + recharge.OrderID + "\r\n");
                    sb.Append("异常信息:" + ex.Message + "\r\n");
                    sb.Append(ex.Source + "\r\n");
                    sb.Append(ex.StackTrace + "\r\n\r\n");

                    log.Error("调用欧飞接口异常：" + sb.ToString());
                    //beway.common.LogManager.Write(sb.ToString());
                }

            }
            return ret;
        }

        /// <summary>
        /// 礼品卡类获取业务
        /// </summary>
        /// <param name="recharge"></param>
        /// <returns></returns>
        public bool GiftCardTrade(Recharge recharge)
        {
            string cardUrl = "http://api2.ofpay.com/order.do?userid={0}&userpws={1}&cardid={2}&cardnum=1&sporder_id={3}&sporder_time={4}&md5_str={5}&version=6.0";

            log4net.Config.XmlConfigurator.Configure();
            string SendUrl = "";

            bool ret = false;
            if (recharge != null && recharge.RCID > 0)
            {
                string ordertime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
                string cardid = recharge.RCTarget; //欧飞商品编码 cpcode                

                //包体=userid+userpws+cardid+cardnum+sporder_id+sporder_time

                string md5str = beway.common.Encryption.Md5Encry32bit(Config.ofUserID + Config.ofPwd + cardid + "1" + recharge.OrderID + ordertime + Ofkeystr).ToUpper();
                SendUrl = string.Format(cardUrl, Config.ofUserID, Config.ofPwd, cardid, recharge.OrderID, ordertime, md5str);
            }

            if (SendUrl != "")
            {
                //log.Info("提卡请求"+SendUrl);

                HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(SendUrl);
                webRequest.ContentType = "application/xml; charset=utf-8";
                webRequest.Method = "get";
                try
                {
                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("gb2312")))
                    {
                        XmlDocument doc = new XmlDocument();
                        string ss = sr.ReadToEnd();
                        //记录到log
                        log.Info(ss);

                        doc.LoadXml(ss);
                        string retcode = doc.SelectSingleNode("//orderinfo/retcode").InnerText;//状态码
                        string retmsg = "";
                        if (retcode == "1")//成功,
                        {
                            //同步返回的礼品卡名称、卡号、密码、有效期
                            StringBuilder sb = new StringBuilder();
                            //卡名称
                            sb.Append(doc.SelectSingleNode("//orderinfo/cardname").InnerText);
                            sb.Append("|");

                            //卡号
                            sb.Append(doc.SelectSingleNode("//orderinfo/cards/card/cardno").InnerText);
                            sb.Append("|");

                            //密码
                            sb.Append(doc.SelectSingleNode("//orderinfo/cards/card/cardpws").InnerText);
                            sb.Append("|");

                            //有效期
                            sb.Append(doc.SelectSingleNode("//orderinfo/cards/card/expiretime").InnerText);
                            sb.Append("|");

                            retmsg = sb.ToString();
                            recharge.RechargeStatus = 1;//充值成功       
                            recharge.RechargeErrorReason = retmsg;
                        }
                        else
                        {
                            retmsg = doc.SelectSingleNode("//orderinfo/err_msg").InnerText;//失败时的原因
                            recharge.RechargeStatus = 0;//失败
                            recharge.RechargeErrorReason = retmsg;
                        }

                        //充值时间
                        recharge.RechargeSuccessTime = System.DateTime.Now;


                        sr.Close();
                        sr.Dispose();
                    }
                    webResponse.Close();

                    ret = true;
                }
                catch (Exception ex)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("****************************\r\n");
                    sb.Append("充值异常时间：" + System.DateTime.Now.ToString() + "\r\n");
                    sb.Append("订单号：" + recharge.OrderID + "\r\n");
                    sb.Append("异常信息:" + ex.Message + "\r\n");
                    sb.Append(ex.Source + "\r\n");
                    sb.Append(ex.StackTrace + "\r\n\r\n");

                    log.Error("调用欧飞接口异常：" + sb.ToString());
                    //beway.common.LogManager.Write(sb.ToString());
                }
            }
            return ret;
        }

        #region 梦网流量包充值业务
        /// <summary>
        /// 梦网流量包充值业务
        /// </summary>
        /// <param name="recharge"></param>
        /// <returns></returns>
        public bool MobileFlowTrade(Recharge recharge)
        {
            string rechargeUrl = ConfigurationSettings.AppSettings["rechargeUrl"];
            //log4net.Config.XmlConfigurator.Configure();
            DateTime now = DateTime.Now;
            string toDay = now.ToString("yyyy-MM-dd");
            if (recharge != null && recharge.RCID > 0)
            {
                //流水号:获取时间戳+随机生成的8位数字
                string timeStamp = System.DateTime.Now.ToString("yyyyMMddHHmmss");
                Random rand = new Random();
                int r = rand.Next(100000000);
                string serialNumber = timeStamp + r;
                //手机号
                string phones = recharge.RCTarget;
                string[] p = phones.Split(',');
                //充值流量包金额
                Nullable<int> amount = recharge.RechargeAmount;

                List<OrderList> orderList = new List<OrderList>();

                //调用相关接口判断手机号是哪个通信运营商
                List<DicPhones> dicP = GetOperator(phones);


                //遍历具体判断可订购日期和充值金额组合
                foreach (var k in dicP)
                {

                    if (k.OpName == "移动")
                    {
                        //中国移动：每月最后2天不能订购
                        int days = DateTime.DaysInMonth(now.Year, now.Month);
                        DateTime datetime = new DateTime(now.Year, now.Month, 1);
                        string lastOneDay = datetime.AddDays(days - 1).ToString("yyyy-MM-dd");
                        string lastTwoDay = datetime.AddDays(days - 2).ToString("yyyy-MM-dd");
                        if (toDay == lastOneDay || toDay == lastTwoDay)
                        {
                            return false;
                        }
                        else
                        {
                            if (amount == 3)
                            {
                                //PID=100010
                                OrderList pModel = GetRechargeModel("100010", orderList, k);
                                orderList.Add(pModel);
                            }
                            else if (amount == 10)
                            {
                                //PID=100012
                                OrderList pModel = GetRechargeModel("100012", orderList, k);
                                orderList.Add(pModel);
                            }
                            else if (amount == 30)
                            {
                                //PID=100014（30/500M）
                                OrderList pModel = GetRechargeModel("100014", orderList, k);
                                orderList.Add(pModel);
                            }
                            else
                            {
                                recharge.RechargeErrorReason = "无此套餐！";
                                return false;
                            }
                        }
                    }
                    if (k.OpName == "电信")
                    {
                        //中国电信：无限制
                        if (amount == 1)
                        {
                            //PID=100000（1/5M）
                            OrderList pModel = GetRechargeModel("100000", orderList, k);
                            orderList.Add(pModel);
                        }
                        else if (amount == 10)
                        {
                            //PID=100004（10/100M）
                            OrderList pModel = GetRechargeModel("100004", orderList, k);
                            orderList.Add(pModel);
                        }
                        else if (amount == 30)
                        {
                            //PID=100006（30/500M） 
                            OrderList pModel = GetRechargeModel("100006", orderList, k);
                            orderList.Add(pModel);
                        }
                        else
                        {
                            recharge.RechargeErrorReason = "无此套餐！";
                            return false;
                        }
                    }
                    if (k.OpName == "联通")
                    {
                        //中国联通：每月第1天不能订购
                        DateTime d1 = new DateTime(now.Year, now.Month, 1);
                        if (toDay == d1.ToString("yyyy-MM-dd"))
                        {
                            return false;
                        }
                        else
                        {
                            if (amount == 3)
                            {
                                //PID = 100022 (10/100M)
                                OrderList pModel = GetRechargeModel("100021", orderList, k);
                                orderList.Add(pModel);
                            }
                            else if (amount == 10)
                            {
                                //PID = 100022 (10/100M)
                                OrderList pModel = GetRechargeModel("100022", orderList, k);
                                orderList.Add(pModel);
                            }
                            else if (amount == 30)
                            {
                                //PID= 100023（30/500M）
                                OrderList pModel = GetRechargeModel("100023", orderList, k);
                                orderList.Add(pModel);
                            }
                            else
                            {
                                recharge.RechargeErrorReason = "无此套餐！";
                                return false;
                            }
                        }
                    }
                }
                #region 废弃代码
                //for (int i = 0; i < tel_Arr.Length; i++) {
                //	if (tel_Arr[i].ToString() == "移动") {
                //		//中国移动：每月最后2天不能订购
                //		int days = DateTime.DaysInMonth(now.Year, now.Month);
                //		DateTime datetime = new DateTime(now.Year, now.Month, 1);
                //		string lastOneDay = datetime.AddDays(days - 1).ToString("yyyy-MM-dd");
                //		string lastTwoDay = datetime.AddDays(days - 2).ToString("yyyy-MM-dd");

                //		if (toDay == lastOneDay || toDay == lastTwoDay) {
                //			return false;
                //		}
                //		else {
                //			if (amount == 3) {
                //				//PID=100010     p[i]
                //				OrderList pModel = orderList.FirstOrDefault(m => m.PID == 100010);
                //				if (pModel != null) {
                //					pModel.Phones += "," + p[i];
                //				}
                //				else {
                //					pModel = new OrderList() { 
                //						PID = 100010,
                //						Phones = p[i]
                //					};
                //				}
                //			}	
                //			if (amount == 10) {
                //				//PID=100012
                //				orderList = new List<OrderList>{
                //					 new OrderList{
                //						PID=100012,
                //						Phones = p[i]
                //					 }
                //				};
                //			}
                //			if (amount == 20) {
                //				//PID=100013
                //			}
                //			if (amount == 30) {
                //				//PID=100012（10/70M） PID=100013 （20/150M）
                //			}
                //		}
                //		//else 调充值方法
                //	}
                //	else if (tel_Arr[i].ToString() == "电信") {
                //		//中国电信：无限制
                //		if (amount == 3) {
                //			//PID=100000（1/5M） PID=100001 （2/10M）
                //		}
                //		if (amount == 10) {
                //			//PID=100004（10/100M）
                //		}
                //		if (amount == 20) {
                //			//PID=100004（10/100M） PID=100004 （10/100M）
                //		}
                //		if (amount == 30) {
                //			//PID=100005（15/200M） PID=100005（15/200M）
                //		}
                //	}
                //	else if (tel_Arr[i].ToString() == "联通") {
                //		//中国联通：每月第1天不能订购
                //		DateTime d1 = new DateTime(now.Year, now.Month, 1);
                //		if (toDay == d1.ToString("yyyy-MM-dd")) {
                //			return false;
                //		}
                //		else {
                //			if (amount == 3) {
                //				//PID=100021（3/20M）
                //			}
                //			if (amount == 10) {
                //				//PID = 100022 (10/100M)
                //			}
                //			if (amount == 20) {
                //				//PID=100022（10/100M） PID=100022 （10/100M）
                //			}
                //			if (amount == 30) {
                //				//PID=100009（15/200M） PID=100009（15/200M）
                //			}
                //		}

                //	}
                //}
                #endregion
                //提交充值请求
                string strJson = SendSubmitPost(recharge, rechargeUrl, serialNumber, orderList);

                //记录返回的原生JSON数据
                log.Info(strJson);

                ////反序列化为对象
                RechargeFlowModel ansModel = Newtonsoft.Json.JsonConvert.DeserializeObject<RechargeFlowModel>(strJson);

                if (ansModel != null)
                {
                    if (ansModel.RtState == "1") //失败
                    {
                        //管理后台：  0记录 , 1成功, 2充值中， 3充值失败
                        int rtRtatus = 3;
                        //recharge.RechargeErrorReason

                        byte[] errArr = Convert.FromBase64String(ansModel.RtMsg);

                        string errReason = System.Text.Encoding.UTF8.GetString(errArr);
                        recharge.RechargeErrorReason = errReason;
                        recharge.RechargeStatus = rtRtatus;
                        #region
                        //StringBuilder sb = new StringBuilder();
                        //sb.Append("****************************\r\n");
                        //sb.Append("充值异常时间：" + System.DateTime.Now.ToString() + "\r\n");
                        //sb.Append("订单号：" + recharge.OrderID + "\r\n");
                        //sb.Append("错误编码：" + ansModel.RtErrCode + "\r\n");
                        //sb.Append("反馈信息描述：" + ansModel.RtMsg + "\r\n");
                        //log.Error("调用梦网流量包失败日志：" + sb.ToString());
                        #endregion
                        return false;
                    }
                    else
                    {
                        recharge.RechargeStatus = 2;
                        recharge.RechargeErrorReason = "正在充值中";
                        return true;
                    }
                }
                else
                    return false;
            }
            return false;
        }


        private static string SendSubmitPost(Recharge recharge, string rechargeUrl, string serialNumber, List<OrderList> orderList)
        {
            List<OrderList> oList = orderList.Distinct().ToList();
            CnxtModel cnModel = new CnxtModel()
            {
                ECOrderId = recharge.OrderID,
                OrderList = oList,
                OrderTime = "",
                Activity = "",
                Operator = "",
            };

            //获取企业密匙
            string keystr = ConfigurationSettings.AppSettings["Enterprisekey"];
            //获取企业代码
            string ecId = ConfigurationSettings.AppSettings["EcId"];
            //序列化
            string cnxtStr = Newtonsoft.Json.JsonConvert.SerializeObject(cnModel);
            //将jsonStr加密MD5(消息体)    
            string encryStr = beway.common.Encryption.Md5Encry32bit(cnxtStr);
            // 对消息体的加密算法：Base64(DES(MD5(消息体) +消息体))
            var encStr = Util.Encryption.DESEncrypt(encryStr + cnxtStr, keystr);
            //获取充值接口代码
            string rechargeEMI = ConfigurationSettings.AppSettings["EMIRecharge"];
            RechargeFlowModel recFlowModel = new RechargeFlowModel()
            {
                BCode = rechargeEMI,
                Ack = "1",
                SqId = serialNumber,
                ECID = ecId,
                Cnxt = encStr
            };
            //将需要传递的数据转为JSON
            string sendJson = Newtonsoft.Json.JsonConvert.SerializeObject(recFlowModel);
            //发送订购请求
            string strJson = HttpHelper.HttpPost(rechargeUrl, sendJson);
            return strJson;
        }
        /// <summary>
        /// 获取各个运营商的手机号码
        /// </summary>
        /// <param name="phones">手机号（可能有多个手机号）</param>
        /// <returns></returns>
        private List<DicPhones> GetOperator(string phones)
        {//需要修改
            //[0]移动 [1]电信 [2]联通
            string[] phonesArray = { "134,135,136,137,138,139,147,150,151,152,154,157,158,159,1703,1705,1706,178,182,183,184,187,188", "133,153,1700,1701,1702,173,177,180,181,189", "130,131,132,145,155,156,1707,1708,1709,1718,1719,175,176,185,186" };
            string[] mobile_Array = phonesArray[0].Split(',');
            string[] telecom_Array = phonesArray[1].Split(',');
            string[] unicom_Array = phonesArray[2].Split(',');
            //手机号
            List<DicPhones> dicList = new List<DicPhones>();

            string[] phone_Arr = phones.Split(',');

            for (int i = 0; i < phone_Arr.Length; i++)
            {
                string subStrFour = "";
                string substr = phone_Arr[i].Substring(0, 3);
                if (substr.Contains("170") || substr.Contains("171"))
                {
                    subStrFour = phone_Arr[i].Substring(0, 4);

                }
                if (mobile_Array.Contains(substr) || mobile_Array.Contains(subStrFour))
                {
                    DicPhones dicModel = dicList.FirstOrDefault(m => m.OpName == "移动");
                    if (dicModel != null)
                    {
                        dicModel.PhonesNum += "," + phone_Arr[i];
                    }
                    else
                    {
                        dicModel = new DicPhones()
                        {
                            OpName = "移动",
                            PhonesNum = phone_Arr[i]
                        };
                    }
                    dicList.Add(dicModel);
                }
                else if (telecom_Array.Contains(substr) || telecom_Array.Contains(subStrFour))
                {
                    DicPhones dicModel = dicList.FirstOrDefault(m => m.OpName == "电信");
                    if (dicModel != null)
                    {
                        dicModel.PhonesNum += "," + phone_Arr[i];
                    }
                    else
                    {
                        dicModel = new DicPhones()
                        {
                            OpName = "电信",
                            PhonesNum = phone_Arr[i]
                        };
                    }
                    dicList.Add(dicModel);
                }
                else if (unicom_Array.Contains(substr) || unicom_Array.Contains(subStrFour))
                {
                    DicPhones dicModel = dicList.FirstOrDefault(m => m.OpName == "联通");
                    if (dicModel != null)
                    {
                        dicModel.PhonesNum += "," + phone_Arr[i];
                    }
                    else
                    {
                        dicModel = new DicPhones()
                        {
                            OpName = "联通",
                            PhonesNum = phone_Arr[i]
                        };
                    }
                    dicList.Add(dicModel);
                }
            }
            List<DicPhones> dic = dicList.Distinct().ToList();
            return dic;
        }
        /// <summary>
        /// 获取充值对象
        /// </summary>
        /// <param name="pid">产品编号</param>
        /// <param name="orderList">订购信息列表</param>
        /// <param name="k">手机对象</param>
        /// <returns></returns>
        private OrderList GetRechargeModel(string pid, List<OrderList> orderList, DicPhones k)
        {

            OrderList pModel = orderList.FirstOrDefault(m => m.PID == pid);
            pModel = new OrderList()
            {
                PID = pid,
                Phones = k.PhonesNum
            };
            return pModel;
        }

        /// <summary>
        /// 梦网流量包充值反馈结果
        /// </summary>
        /// <param name="jsonStr">反馈json字符串</param>
        /// <returns></returns>
        public string FlowResultReceive(string jsonStr)
        {
            int ret = 0;
            //获取企业密匙
            string strKey = ConfigurationSettings.AppSettings["Enterprisekey"];
            //将请求报文转化为model
            RechargeFlowModel rm = Newtonsoft.Json.JsonConvert.DeserializeObject<RechargeFlowModel>(jsonStr);
            //获取报文体
            string cnxtStr = rm.Cnxt;
            //解密
            string jmStr = Util.Encryption.DESDecrypt(cnxtStr, strKey);
            //截取未加密的消息体
            string strJson = jmStr.Substring(jmStr.IndexOf('{'));

            FlowResultModel frm = Newtonsoft.Json.JsonConvert.DeserializeObject<FlowResultModel>(strJson);

            //将返回的错误代码，在数据库中存入相应的错误信息（最可能发生的）
            string errReason = "";
            if (frm.ErrCode == "9999")
                errReason = "内部错误";
            else if (frm.ErrCode == "2003")
                errReason = "订单手机号不正确";
            else if (frm.ErrCode == "2009")
                errReason = "客户自定义订单号已存在";
            else if (frm.ErrCode == "2011")
                errReason = "余额不足";
            else if (frm.ErrCode == "2010")
                errReason = "手机号重复次数超过上限";
            else if (frm.ErrCode == "2012")
                errReason = "扣费失败";
            else if (frm.ErrCode == "2015")
                errReason = "订单号不能为空";
            else if (frm.ErrCode == "0000")//
                errReason = "";
            else if (frm.ErrCode == "1")
                errReason = "未定义错误";
            else
                errReason = frm.ErrCode;

            //管理后台：  0初始记录, 1成功,2充值中， 3充值失败 对应 反馈订购状态：0-订购中 1-订购成功 2-订购失败
            int rtStatus = 0;
            if (frm.OrderState == "2")
            {
                rtStatus = 3;
            }
            else
            {
                rtStatus = Convert.ToInt32(frm.OrderState);
            }
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                Recharge q = db.Recharge.SingleOrDefault(u => u.OrderID == frm.ecOrderId);
                if (q != null && q.RechargeStatus == 2)
                {
                    q.RechargeErrorReason = errReason;
                    q.RechargeSuccessTime = DateTime.Now;
                    q.RechargeStatus = rtStatus;
                    ret = db.SaveChanges();
                }
            }
            //流水号
            string timeStamp = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            Random rand = new Random();
            int r = rand.Next(100000000);
            string serialNumber = timeStamp + r;
            //获取反馈接口代码
            string feedBackEMI = ConfigurationSettings.AppSettings["EMIFeedBack"];
            //返回应答报文
            AnswerModel rfm = new AnswerModel()
            {
                BCode = feedBackEMI,
                Ack = "2",
                SqId = serialNumber,
                RtState = "0",
                Cnxt = "",
            };
            string resJsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(rfm);
            return resJsonStr;
        }
        /// <summary>
        /// 流量包充值查询
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orderNo"></param>
        /// <param name="rcType"></param>
        /// <returns></returns>
        public Recharge GetByUIdAndOrderNoAndRcType(int userId, string orderNo, int rcType)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.SingleOrDefault(m => m.UserID == userId && m.OrderID == orderNo && m.RCType == rcType);
                return q;
            }
        }
        #endregion

        /// <summary>
        /// 新增充值订单
        /// </summary>
        /// <param name="rm">实体</param>
        /// <returns></returns>
        public int Add(Recharge rm)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                db.Recharge.Add(rm);
                return db.SaveChanges();
            }
        }

        /// <summary>
        /// 返回用户的订单列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public List<Recharge> OrderList(int userId)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var list = db.Recharge.Where(r => r.UserID == userId);
                return list.ToList();
            }
        }

        /// <summary>
        /// 新增充值记录，并判断调用系统提供的订单号是否唯一
        /// </summary>
        /// <param name="rm"></param>
        /// <returns></returns>
        public int AddForUniqueOrderNo(Recharge rm)
        {
            int ret = 0;
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    int hasOrderNo = db.Recharge.Count(m => m.UserID == rm.UserID && m.UserOrderNo == rm.UserOrderNo);
                    if (hasOrderNo == 0)
                    {
                        db.Recharge.Add(rm);
                        ret = db.SaveChanges();
                    }
                    //提交事务
                    transaction.Complete();
                }
            }
            return ret;
        }

        /// <summary>
        /// 获得分页的充值记录列表
        /// </summary>
        /// <param name="page">page Index</param>
        /// <param name="rows">page size </param>
        /// <param name="userId">充值账户id</param>
        /// <param name="adminId">管理员id</param>
        /// <param name="orderNo">充值账户订单号</param>
        /// <param name="rcTaget">充值手机/QQ号</param>
        /// <param name="beginTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="ListCount">总数量</param>
        /// <returns></returns>
        public List<RechargeView> RechargeList(int page, int rows, int userId, int adminId,string orderNo, string rcTarget, int rcStatus, DateTime? beginTime, DateTime? endTime, out int ListCount, int DiscountFlag = 0)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                IQueryable<RechargeView> q = from r in db.Recharge
                                             join u in db.ReUser on r.UserID.Value equals u.UserID
                                             orderby r.RCID descending
                                             select new RechargeView()
                                             {
                                                 OrderAmount = r.OrderAmount,
                                                 OrderID = r.OrderID,
                                                 OrderTime = r.OrderTime,
                                                 PayStatus = r.PayStatus,
                                                 PaySuccessTime = r.PaySuccessTime,
                                                 RCID = r.RCID,
                                                 RCTarget = r.RCTarget,
                                                 RCType = r.RCType,
                                                 RechargeAmount = r.RechargeAmount,
                                                 RechargeErrorReason = r.RechargeErrorReason,
                                                 RechargeStatus = r.RechargeStatus,
                                                 RechargeSuccessTime = r.RechargeSuccessTime,
                                                 UserID = r.UserID,
                                                 UserOrderNo = r.UserOrderNo,
                                                 UserTitle = u.UserTitle,
                                                 AdminId = u.AdminId,
                                                 RechDiscountFlag = r.RechDiscountFlag
                                             };

                if (userId > 0)
                {
                    q = q.Where(m => m.UserID == userId);
                }

                if (adminId > 0)
                {
                    q = q.Where(m => m.AdminId == adminId);
                }

                if (rcStatus > -1)
                {
                    if (rcStatus == 1) //1成功
                    {
                        q = q.Where(m => m.RechargeStatus == rcStatus);
                    }
                    else
                    {
                        //0未充值 >1失败
                        q = q.Where(m => (m.RechargeStatus == 0 || m.RechargeStatus > 1));
                    } 
                }

                if (!string.IsNullOrEmpty(orderNo))
                {
                    q = q.Where(m => m.UserOrderNo == orderNo);
                }

                if (!string.IsNullOrEmpty(rcTarget))
                {
                    q = q.Where(m => m.RCTarget == rcTarget);
                }
                if (beginTime != null)
                {
                    q = q.Where(m => m.OrderTime >= beginTime);
                }

                if (endTime != null)
                {
                    q = q.Where(m => m.OrderTime < endTime);
                }

                if (DiscountFlag > 0)
                {
                    if (DiscountFlag == 3)
                    {
                        q = q.Where(m => m.RechDiscountFlag > 0);
                    }
                    else
                    {
                        q = q.Where(m => m.RechDiscountFlag == DiscountFlag);
                    }
                }

                //q = q.OrderByDescending(m => m.UserID);

                ListCount = q.Count();

                var adm = q.Skip((page - 1) * rows).Take(rows).ToList();
                return adm;
            }
        }
        /// <summary>
        /// 根据商户的id和订单号查询订单实体
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="orderNo">订单号</param>
        /// <returns></returns>
        public Recharge GetByUserIdAndOrderNo(int userId, string orderNo)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.SingleOrDefault(m => m.UserID == userId && m.UserOrderNo == orderNo);
                return q;
            }
        }

        /// <summary>
        /// 根据ID，查询充值实体
        /// </summary>
        /// <param name="rcId"></param>
        /// <returns></returns>
        public Recharge GetById(int rcId)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.SingleOrDefault(m => m.RCID == rcId);
                return q;
            }
        }

        /// <summary>
        /// 更新充值实体
        /// </summary>
        /// <param name="re"></param>
        /// <returns></returns>
        public bool Update(Recharge re)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.SingleOrDefault(m => m.RCID == re.RCID);
                q.OrderAmount = re.OrderAmount;
                q.OrderID = re.OrderID;
                q.OrderTime = re.OrderTime;
                q.PayStatus = re.PayStatus;
                q.PaySuccessTime = re.PaySuccessTime;
                q.RCID = re.RCID;
                q.RCTarget = re.RCTarget;
                q.RCType = re.RCType;
                q.RechargeAmount = re.RechargeAmount;
                q.RechargeErrorReason = re.RechargeErrorReason;
                q.RechargeStatus = re.RechargeStatus;
                q.RechargeSuccessTime = re.RechargeSuccessTime;
                q.UserID = re.UserID;
                q.UserOrderNo = re.UserOrderNo;
                return db.SaveChanges() > 0;
            }
        }

        #region 欧飞充值手机上网流量包
        /// <summary>
        /// 欧飞充值手机上网流量包,目前三家运营商共有用面值只有10元，30元，
        /// 其中移动10元对应70M流量，联通电信10元对应100M流量
        /// 30元均对应500M流量
        /// </summary>
        /// <param name="recharge"></param>
        /// <returns></returns>
        public bool OfFlowOrderTrade(Recharge recharge)
        {
            string rechargeurl = "http://A780868.api2.ofpay.com/flowOrder.do?userid={0}&userpws={1}&phoneno={2}&perValue={3}&flowValue={4}&range={5}&effectStartTime={6}&effectTime={7}&sporderId={8}&md5Str={9}&retUrl={10}&version=6.0";
            //包体= userid + userpws + phoneno + perValue + flowValue + range + effectStartTime + effectTime+ sporderId
            //回调通知地址
            string retUrl = "http://" + Config.SiteUrl + "/Recharge/RecResult";//欧飞通知的结果
            string sendUrl = "";
            bool ret = false;
            if (recharge != null && recharge.RCID > 0)
            {
                //生效时间 1（当日）、2（次日）、3（次月），移动月末两天不能充
                int effectStartTime = 1;

                //有效期 1(当月有效) 2(30天有效) 3(半年有效) 4(3个月有效) 5(2个月有效) 6(6个月有效)
                int effectTime = 1;

                //使用范围 1（省内）、 2（全国）
                int range = 2;

                //流量值，按照流量产品文档中对应商品输入
                string flowValue =recharge.RechargeErrorReason;
                //if (recharge.RechargeAmount == 10)
                //{
                //    if (ChinaMobileNoPrefix.Contains(recharge.RCTarget.Substring(0, 3)))
                //    {
                //        flowValue = "70M"; //移动10元只有70M
                //    }
                //    else
                //    {
                //        flowValue = "100M"; //联通，电信10元100M
                //    }
                //}
                //else
                //{
                //    flowValue = "500M";//30元三家均500M
                //}

                string md5str = beway.common.Encryption.Md5Encry32bit(Config.ofUserID + Config.ofPwd + recharge.RCTarget + recharge.RechargeAmount + flowValue + range + effectStartTime + effectTime + recharge.OrderID + Ofkeystr).ToUpper();
                sendUrl = string.Format(rechargeurl, Config.ofUserID, Config.ofPwd, recharge.RCTarget, recharge.RechargeAmount, flowValue, range, effectStartTime, effectTime, recharge.OrderID, md5str, retUrl);
            }
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(sendUrl);
            webRequest.ContentType = "application/xml; charset=utf-8";
            webRequest.Method = "get";
            try
            {
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("gb2312")))
                {
                    XmlDocument doc = new XmlDocument();
                    string ss = sr.ReadToEnd();

                    doc.LoadXml(ss);
                    string retcode = doc.SelectSingleNode("//orderinfo/retcode").InnerText;//状态码
                    string rc = "", errmsg = "";
                    if (retcode == "1")//成功
                    {
                        //有可能的值 0充值中，1充值成功，9充值撤销（可退款）
                        rc = doc.SelectSingleNode("//orderinfo/game_state").InnerText;//提交成功，true
                    }
                    else
                    {
                        errmsg = doc.SelectSingleNode("//orderinfo/err_msg").InnerText;//失败时的原因
                        recharge.RechargeErrorReason = errmsg;
                        rc = retcode;//可能的值 0充值中,  1成功, 9充值失败，可以退款
                    }
                    if (rc == "1")
                    {
                        recharge.RechargeStatus = 1;//充值成功
                    }
                    else if (rc == "0")
                    {
                        recharge.RechargeStatus = 2;//充值中
                        recharge.RechargeErrorReason = "正在充值中";
                    }
                    else if (rc == "9")
                    {
                        recharge.RechargeStatus = 3;//充值失败，可以退款
                    }
                    else//等于空的情况
                    {
                        recharge.RechargeStatus = 0;//错误
                        recharge.RechargeErrorReason = "充值平台返回结果未知(retcode:" + rc + ")";
                    }
                    recharge.RechargeSuccessTime = System.DateTime.Now;
                    
                    ret = true;

                    sr.Close();
                    sr.Dispose();
                }
                webResponse.Close();
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("****************************\r\n");
                sb.Append("充值异常时间：" + System.DateTime.Now.ToString() + "\r\n");
                sb.Append("订单号：" + recharge.OrderID + "\r\n");
                sb.Append("异常信息:" + ex.Message + "\r\n");
                sb.Append(ex.Source + "\r\n");
                sb.Append(ex.StackTrace + "\r\n\r\n");

                log.Error("调用欧飞流量接口异常：" + sb.ToString());
                //beway.common.LogManager.Write(sb.ToString());
            }

            return ret;

        }
        #endregion

        /// <summary>
        /// 查询所有待充值的记录--黑龙江移动(paystatus=1)
        /// </summary>
        /// <returns></returns>
        public static List<RechargeView> QueryFlowStack()
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = from r in db.Recharge
                        where r.PayStatus == 1 && r.RCType == 4 && r.RechargeStatus == 0 
                        orderby r.OrderTime ascending
                        select new RechargeView
                        {
                            OrderAmount = r.OrderAmount,
                            OrderID = r.OrderID,
                            OrderTime = r.OrderTime,
                            PayStatus = r.PayStatus,
                            PaySuccessTime = r.PaySuccessTime,
                            RCID = r.RCID,
                            RCTarget = r.RCTarget,
                            RCType = r.RCType,
                            RechargeAmount = r.RechargeAmount,
                            RechargeErrorReason = r.RechargeErrorReason,
                            RechargeStatus = r.RechargeStatus,
                            RechargeSuccessTime = r.RechargeSuccessTime,
                            UserID = r.UserID,
                            UserOrderNo = r.UserOrderNo,
                            BatchOrderNo = r.BatchOrderNo
                        };
                if (q != null)
                {
                    
                    return q.Distinct(p => p.RCTarget).ToList();
                }
                else
                    return null;
            }
        }

        /// <summary>
        /// 通过RCID修改支付状态、批次编号--黑龙江移动
        /// </summary>
        /// <param name="re"></param>
        /// <returns></returns>
        public static bool UpdatePayStatus(Recharge re)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {

                var q = db.Recharge.SingleOrDefault(m => m.RCID == re.RCID);
                q.RechargeStatus = re.RechargeStatus;
                q.BatchOrderNo = re.BatchOrderNo;
                q.PaySuccessTime = System.DateTime.Now;
                q.RechargeErrorReason = re.RechargeErrorReason;
                return db.SaveChanges() > 0;
            }
        }
        /// <summary>
        /// 通过通知结果改变充值状态
        /// </summary>
        /// <param name="re"></param>
        /// <returns></returns>
        public bool UpdateByBatchNoAndRCTarget(Recharge re)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.FirstOrDefault(m => m.RCTarget == re.RCTarget && m.BatchOrderNo == re.BatchOrderNo && m.PayStatus == 1 && m.RechargeStatus == 2);
                if (q != null)
                {
                    q.RechargeStatus = re.RechargeStatus;
                    q.RechargeErrorReason = re.RechargeErrorReason;
                    q.RechargeSuccessTime = re.RechargeSuccessTime;
                    return db.SaveChanges() > 0;
                }
                else
                    return false;
            }
        }
        /// <summary>
        /// 通过RCID修改BatchOrderNo
        /// </summary>
        /// <param name="re"></param>
        /// <returns></returns>
        public static bool UpdateBatchNoByRCID(Recharge re)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.SingleOrDefault(m => m.RCID == re.RCID);
                q.BatchOrderNo = re.BatchOrderNo;
                return db.SaveChanges() > 0;
            }
        }

        /// <summary>
        /// 统计项目累计充值金额，不含已确定充值失败的，目前只汇总话费、Q币和欧飞10元、30元流量
        /// （后续补充时也会累计）
        /// </summary>
        /// <param name="reUserId">项目Id</param>
        /// <returns></returns>
        public decimal SumRechAmountByReUser(int reUserId)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.Where(m => (m.RCType == 1 || m.RCType == 2 || m.RCType == 4) && (m.RechargeStatus == 1 || m.RechargeStatus == 2)); //只统计话费或qq币的累计,（两种一起统计）,并且状态为充值中2或充值成功1，未充值或失败的状态0不统计在内
                if (reUserId > 0)
                {
                    q = q.Where(m => m.UserID == reUserId);
                }
                int? sum = q.Sum(m => m.RechargeAmount);
                if (sum == null)
                {
                    sum = 0;
                }

                return (decimal)sum;
            }
        }

        /// <summary>
        /// 统计项目累计充值金额，不含已确定充值失败的，目前只汇总话费、Q币和欧飞10元、30元流量
        /// （后续补充时也会累计）
        /// </summary>
        /// <param name="reUserId">项目Id</param>
        /// <param name="beginTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public decimal SumRechAmountByReUserAndTime(int reUserId,DateTime beginTime,DateTime endTime)
        {
            using (BewayValueAddedEntities db = new BewayValueAddedEntities())
            {
                var q = db.Recharge.Where(m => (m.RCType == 1 || m.RCType == 2 || m.RCType == 4) 
                && (m.RechargeStatus == 1 || m.RechargeStatus == 2)
                && m.OrderTime>=beginTime && m.OrderTime<endTime
                ); //只统计话费或qq币的累计,（两种一起统计）,并且状态为充值中2或充值成功1，未充值或失败的状态0不统计在内
                if (reUserId > 0)
                {
                    q = q.Where(m => m.UserID == reUserId);
                }

                int? sum = q.Sum(m => m.RechargeAmount);
                if (sum == null)
                {
                    sum = 0;
                }

                return (decimal)sum;
            }
        }
    }
}
